package com.junqi.live.room.common.annotation;

import com.junqi.common.entity.AjaxResult;
import com.junqi.common.entity.ChatMessageDto;
import com.junqi.common.entity.RedisKeyManager;
import com.junqi.live.room.common.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 限流注解
 * 上行限速控制（丢弃）策略：针对单个聊天室的消息上行的限速控制，我们默认为 100 条 / 秒
 */
@Aspect
@Component
@Slf4j
public class RateLimitAspect {

    @Around("@annotation(rateLimit)")
    public Object rateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || !(args[0] instanceof ChatMessageDto)) {
            return joinPoint.proceed(); // 如果参数不符合，直接放行
        }
        ChatMessageDto dto = (ChatMessageDto) args[0];
        String roomId = dto.getRoomId();
        //int type = dto.getMsgType();
        long maxRequests = rateLimit.maxRequests();
        // Redis 中计数
        long currentCount = RedisUtil.increment(RedisKeyManager.generateKey(RedisKeyManager.ROOM_RATE_LIMIT, roomId), 1, 1);
        if (currentCount <= maxRequests) {
            // 未达到限流阈值，放行
            return joinPoint.proceed();
        }else {
            // 超过最大限流阈值 直接返回成功
            log.warn("超过最大限流阈值 for roomId={}, count={}", roomId, currentCount);
            return AjaxResult.success();
        }
    }

}
